import http from './http'

export interface OrderItem {
  ID?: number
  product_id: number
  product_name: string
  quantity: number
  price: number
  unit?: string
  spec?: string
  brand?: string
  made_in?: string
  batch_no?: string
  expiry_date?: string
  remark?: string
}

export interface Order {
  ID?: number
  order_no?: string
  customer: string
  customer_phone?: string
  customer_addr?: string
  responsible: string
  total_price: number
  status?: string
  payment_status?: string
  notes?: string
  delivery_date?: string
  delivery_address?: string
  delivery_contact?: string
  delivery_phone?: string
  shipment_no?: string
  warehouse?: string
  packager?: string
  shipper?: string
  shipping_method?: string
  freight?: number
  tax_rate?: number
  tax_amount?: number
  discount?: number
  final_amount?: number
  items: OrderItem[]
}

export interface OrderSearchParams {
  customer?: string
  status?: string
  payment_status?: string
  start_date?: string
  end_date?: string
  warehouse?: string
  page?: number
  pageSize?: number
}

export interface DeliveryForm {
  delivery_date: string
  delivery_address: string
  delivery_contact: string
  delivery_phone: string
  warehouse: string
  packager?: string
  shipper?: string
  shipping_method: string
  freight: number
  tax_rate: number
  discount: number
}

export interface OutboundForm {
  outbound_date: string
  operator: string
  notes?: string
}

export interface ShipmentForm {
  ship_date: string
  tracking_no: string
  carrier: string
  shipper: string
  notes?: string
}

export interface BatchStatusUpdate {
  order_ids: number[]
  status: string
}

export const ordersApi = {
  // 获取订单列表
  getList: (params?: OrderSearchParams) => http.get('/orders', { params }),

  // 获取单个订单
  getDetail: (id: number) => http.get(`/orders/${id}`),

  // 创建订单
  create: (order: Omit<Order, 'ID' | 'order_no' | 'status' | 'payment_status'>) => http.post('/orders', order),

  // 更新订单状态
  updateStatus: (id: number, status: string) => http.put(`/orders/${id}/status`, { status }),

  // 更新支付状态
  updatePayment: (id: number, payment_status: string) => http.put(`/orders/${id}/payment`, { payment_status }),

  // 生成送货单
  generateDelivery: (id: number, data: DeliveryForm) => http.post(`/orders/${id}/delivery`, data),

  // 获取打印数据
  getPrintData: (id: number) => http.get(`/orders/${id}/print`),

  // 确认出库
  confirmOutbound: (id: number, data: OutboundForm) => http.put(`/orders/${id}/outbound`, data),

  // 确认发货
  confirmShipment: (id: number, data: ShipmentForm) => http.put(`/orders/${id}/ship`, data),

  // 删除订单
  delete: (id: number) => http.delete(`/orders/${id}`),

  // 获取订单统计
  getStats: () => http.get('/orders/stats'),

  // 获取待出库订单
  getPendingOutbound: () => http.get('/orders/outbound/pending'),

  // 获取待发货订单
  getPendingShipment: () => http.get('/orders/shipment/pending'),

  // 批量更新订单状态
  batchUpdateStatus: (data: BatchStatusUpdate) => http.put('/orders/batch/status', data)
} 